jQuery(function(){
    jQuery(document).ready(function () {
		var serverItemData = {};
		serverItemData.schemeID=jQuery('#schemeID').val();
		var serverItemTable;
	////删除维护方案
	jQuery('.delBtn').on('click', function () {
		var selects=getSelect("#resultSchemeTable",1);
		var url=window.rootPath+"/ui/afterSaleMaintain/delScheme";
		$("#checkAllScheme").prop("checked", false);
		delSelect(selects,url,serverSchemeTable)
	});
	///新建维护方案
	jQuery('.addBtn').on('click',function(){
			var treeObj = $.fn.zTree.getZTreeObj("deviceTree");
			var nodes = treeObj.getCheckedNodes(true);
			if(nodes.length>1){
				$.springLemonDialog({
					content: '不能同时为多个设备添加方案！',// 确认文本
					clickButton: function (sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
			}
			else if(nodes.length==0){
				$.springLemonDialog({
					content: '请选择一个设备再添加方案',// 确认文本
					clickButton: function (sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
			}else if(nodes.length==1) {
				if (nodes[0].parentId==0) {
					var type =nodes[0].name;
					var deviceID = nodes[0].id;
					var deviceType =nodes[0].name;
				}
				else {
					var type =nodes[0].father;
					var deviceID = nodes[0].id;
					var deviceType = nodes[0].name;
				}
				jQuery('#schemeID').val('');
				jQuery('#type').val(type);
				jQuery('#deviceID').val(deviceID);
				jQuery('#deviceType').val(deviceType);
				jQuery('#schemeName').val('');
				jQuery('#schemeCode').val('');
				jQuery("#itemId").val('');
				jQuery("#maintainPeriod").val('');
				jQuery("#maintainProject").val('');
				jQuery("#announcement").val('');
				jQuery("#memo").val('');
				document.getElementById('schemeCode').readOnly=false;
				document.getElementById('schemeName').readOnly=false;
				jQuery(".saveSchemeBtn").attr("disabled", false);
				serverItemData.schemeID=jQuery('#schemeID').val();
				serverItemTable.draw();
				jQuery('#maintainSchemeModal').modal('show');
				//window.location = window.rootPath+"/ui/afterSaleMaintain/add/"+type+"/"+deviceID+"/"+deviceType;
			}
		});
	///编辑维护方案
	jQuery('.editBtn').on('click',function(){
		var selects=getSelect("#resultSchemeTable",1);
		   if(selects.length>1){
			   $.springLemonDialog({
			         content: '只能编辑一条记录',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			             $(this).closeDialog(modal);
			         }
			   }); 
		   }
		   else if(selects.length==0){
			   $.springLemonDialog({
			         content: '请选择要编辑的记录',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			             $(this).closeDialog(modal);
			         }
			   }); 
		   }else if(selects.length==1){
			 var id = selects[0].id;
			 jQuery('#schemeID').val(id);
			 jQuery('#type').val(selects[0].type);
			 jQuery('#deviceID').val(selects[0].deviceID);
			 jQuery('#deviceType').val(selects[0].deviceType);
			 jQuery('#schemeName').val(selects[0].schemeName);
			 jQuery('#schemeCode').val(selects[0].schemeCode);
			   document.getElementById('schemeCode').readOnly=false;
			   document.getElementById('schemeName').readOnly=false;
			   jQuery(".saveSchemeBtn").attr("disabled", false);
			 serverItemData.schemeID=id;
			 serverItemTable.draw(false);
			 jQuery('#maintainSchemeModal').modal('show');
			 //window.location = window.rootPath+"/ui/afterSaleMaintain/editScheme/"+id;
		   }
	});
		//////初始化设备的树结构//////////
		var modalSetting = {
			edit : {
				enable : true,
				showRemoveBtn : false,
				showRenameBtn : false
			},
			data : {
				simpleData : {
					enable : true,
					idKey : "id",
					pIdKey : "parentId",
					rootParentId : 0
				}
			},
			check : {
				enable : true,
				chkStyle : "radio"

			},
			view : {
				showLine : true
			},
			callback:{
				onCheck: showNode
			}
		};
		var url =window.rootPath+"/ui/afterSaleMaintain/getTree";
		var firstNode = [];
		jQuery.ajax({
			url: encodeURI(url),
			cache: false,
			type: "get",
			dataType: "json",
			contentType: "application/json;charset=utf-8",//解决返回数据中的中文乱码问题
			success: function (data) {
				firstNode.push({
					id: 0,
					name: "设备分类",
					open: "true",
					nocheck :"true"
				});
				if (data.deviceType.length > 0) {
					for (var i = 0; i < data.deviceType.length; i++) {
						  firstNode.push(data.deviceType[i]);
					}
				}
				$.fn.zTree.init($("#deviceTree"), modalSetting, firstNode);
			}
		});
//获取维护方案页面数据 服务器分页
		var serverSchemeData = {};
		serverSchemeData.deviceID="null";
		var serverSchemeTable;
		serverSchemeTable = jQuery('#resultSchemeTable').DataTable({
			"serverSide": true,
			"ordering": false,
			"iDisplayLength": 5,
			"ajax": {
				"dataType": "json",
				"type": "get",
				"cache": false,
				"url":window.rootPath+ '/ui/afterSaleMaintain/getpage',
				"data": function (d) {
					return $.extend({}, d, serverSchemeData);
				}
			},
			columns: [
				{
					data: null
				},
				{
					data: null,
					defaultContent: "",
					render: function (data, type, full, meta) {
						var id=data.id
						var operate ='<input type="checkbox" class="checkchildScheme">';
						return operate;
					}
				},
				{
					data: 'schemeName'
				},
				{
					data: 'schemeCode'
				},
				{
					data: 'type'
				},
				{
					data: 'deviceType'
				}
			],
			"drawCallback": function (oSettings) {
				var k = 0;
				var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

				for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
					$('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
					k++;
				}
			}
		});
////////点击显示节点相关的方案///////
		function showNode(event, treeId, treeNode){
			var nodeId=treeNode.id;
			serverSchemeData.deviceID=nodeId;
			serverSchemeTable.draw(true);
		}
	//列表中的全选
    $("#checkAllScheme").click(function(){
    	var check = $(this).prop("checked");
        $(".checkchildScheme").prop("checked", check);
	});
    
  //获取维护项目页面数据 服务器分页
    jQuery(document).ready(function () {
	serverItemTable = jQuery('#resultItemTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url":window.rootPath+ '/ui/afterSaleMaintain/getItem',
            "data": function (d) {
                return $.extend({}, d, serverItemData);
            }
        },
        columns: [
            {
            	data: null
            },
            {
	            data: null,
	            defaultContent: "",
	            render: function (data, type, full, meta) {
	            	var id=data.id
	            	var operate ='<input type="checkbox" class="checkchildItem">';
	            	return operate;
	            }   
            },
            {
                data: 'maintainPeriod'
            },
            {
            	data: 'maintainProject'
            },
            {
                data: 'announcement'
            },
            {
                data: 'memo'
            }
            ],
        "drawCallback": function (oSettings) {
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                k++;
            }
        }
    });
	
	////删除维护项目
	jQuery('.delItemBtn').on('click', function () {
		var selects=getSelect("#resultItemTable",1);
		var url=window.rootPath+"/ui/afterSaleMaintain/delItem";
		$("#checkAllItem").prop("checked", false);
		delSelect(selects,url,serverItemTable);
	});
    ////清空维护项目
	jQuery('.resetBtn').on('click', function () {
				jQuery("#itemId").val("");
				jQuery("#maintainPeriod").val("");
				jQuery("#maintainProject").val("");
				jQuery("#announcement").val("");
				jQuery("#memo").val("");
		});
	/////编辑维护项目
    jQuery('.editItemBtn').on('click', function () {
	   var selects=getSelect("#resultItemTable",1);
	   if(selects.length>1){
		   $.springLemonDialog({
		         content: '只能编辑一条记录',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		   }); 
	   }
	   else if(selects.length==0){
		   $.springLemonDialog({
		         content: '请选择要编辑的记录',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		   }); 
	   }else if(selects.length==1){
		 var itemId=selects[0].id;
		 var maintainPeriod=selects[0].maintainPeriod;
		 var maintainProject=selects[0].maintainProject;
		 var announcement=selects[0].announcement;
		 var memo=selects[0].memo;
		 jQuery("#itemId").val(itemId);
	     jQuery("#maintainPeriod").val(maintainPeriod);
	     jQuery("#maintainProject").val(maintainProject);
	     jQuery("#announcement").val(announcement);
	     jQuery("#memo").val(memo);
	   }
   });
    //方案编号输入框失去焦点后验证方案编号有效性
    jQuery("#schemeCode").blur( function (){
    	var schemeID=jQuery("#schemeID").val();
    	var schemeCode=jQuery("#schemeCode").val();
    	if (schemeID==null||schemeID==''){
    		schemeID = 'null';
    	}
    	if (schemeCode!=''){
    		var urlValid=window.rootPath+"/ui/afterSaleMaintain/validSchemeCode/"+schemeID+"/"+schemeCode;
        	jQuery.ajax({
                url:encodeURI(urlValid),
                cache:false,
                type :"get",
                dataType:"json",
                contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
                success:function(data){
                	if(data.state==1){
                		alert("方案编号已存在，请修改！");
                	}
                }
        	});
    	}
    });
	//保存维护方案
	jQuery('.saveSchemeBtn').on('click', function (){
			if(jQuery("#maintainSchemeAtrrForm") && !jQuery("#maintainSchemeAtrrForm").Validform({tiptype:3, showAllError:true}).check(false)){
				return;
			};
			var schemeID=jQuery("#schemeID").val();
			var type=jQuery("#type").val();
			var deviceID=jQuery("#deviceID").val();
			var deviceType=jQuery("#deviceType").val();
			var schemeCode=jQuery("#schemeCode").val();
			var schemeName=jQuery("#schemeName").val();
			var id = schemeID;
			if (schemeID==null||schemeID==''){
				id = 'null';
			}
			var urlValid=window.rootPath+"/ui/afterSaleMaintain/validSchemeCode/"+id+"/"+schemeCode;
			jQuery.ajax({
				url:encodeURI(urlValid),
				cache:false,
				type :"get",
				dataType:"json",
				contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
				success:function(data){
				if (data.state=="1"){
					alert("方案编号已存在，请修改！");
					jQuery(".saveItemBtn").attr("disabled", false);
					return;
				}else{
				if (schemeID==""){//新增
				var url0=window.rootPath+"/ui/afterSaleMaintain/saveScheme";
				var d = {
					"type": type,
					"deviceID": deviceID,
					"deviceType": deviceType,
					"schemeCode": schemeCode,
					"schemeName": schemeName
				};
					jQuery(".saveSchemeBtn").attr("disabled", true);
				jQuery.ajax({
					type: 'post',
					url: encodeURI(url0),
					data: JSON.stringify(d),
					dataType: 'json',
					contentType: 'application/json;charset=utf-8',
					success: function (data) {
						var schemeId=data.schemeId;
						jQuery("#schemeID").val(schemeId);
						document.getElementById('schemeCode').readOnly=true;
						document.getElementById('schemeName').readOnly=true;
						serverItemData.schemeID=schemeId;
						serverItemTable.draw(true);
					}
				});
			}else{//编辑
				var url=window.rootPath+'/api/maintainSchemes/'+schemeID;
				var d = {
					"type": type,
					"deviceID": deviceID,
					"deviceType": deviceType,
					"schemeCode": schemeCode,
					"schemeName": schemeName
				};
				jQuery.ajax({
					url:encodeURI(url),
					type:'patch',
					data: JSON.stringify(d),
					dataType: 'json',
					contentType: 'application/json;charset=utf-8',
					success: function (data) {
						document.getElementById('schemeCode').readOnly=true;
						document.getElementById('schemeName').readOnly=true;
						serverItemTable.draw(false);
					}
				});
			}
					$.springLemonDialog({
						content: '当前维护方案保存成功！',// 确认文本
						clickButton: function (sender, modal, index) {// 按钮事件处理
							$(this).closeDialog(modal);
						}
					});
					jQuery(".saveSchemeBtn").attr("disabled", true);
				}
		}
	});
	});
	//保存维护项目
	jQuery('.saveItemBtn').on('click', function (){
        if(jQuery("#maintainPeriod") && !jQuery("#maintainPeriod").Validform({tiptype:3, showAllError:true}).check(false)){
            return;
        };
        var schemeID=jQuery("#schemeID").val();
        var itemId=jQuery("#itemId").val();
        var maintainPeriod=jQuery("#maintainPeriod").val();
        var maintainProject=jQuery("#maintainProject").val();
        var announcement=jQuery("#announcement").val();
        var memo=jQuery("#memo").val();
        jQuery(".saveItemBtn").attr("disabled", true);
		if (schemeID==""){//当前维护方案没有保存
			$.springLemonDialog({
				content: '当前维护方案没有保存，请先保存设备方案！',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
	   }else{
		if (maintainPeriod!=''||maintainProject!=''||announcement!=''||memo!=''){
				if (itemId==""){//新增
					var api = window.rootPath + "/api/maintainItems";
					var data = {
						"maintainSchemeID": schemeID,
						"maintainPeriod": maintainPeriod,
						"maintainProject": maintainProject,
						"announcement": announcement,
						"memo": memo
					};
					jQuery.ajax({
						type: 'post',
						url: api,
						data: JSON.stringify(data),
						dataType: 'json',
						contentType: 'application/json;charset=utf-8',
						success: function (data) {
							jQuery("#itemId").val('');
							jQuery("#maintainPeriod").val('');
							jQuery("#maintainProject").val('');
							jQuery("#announcement").val('');
							jQuery("#memo").val('');
							serverItemData.schemeID=schemeID;
							serverItemTable.draw(true);
							jQuery(".saveItemBtn").attr("disabled", false);
						}
					});
				}else{
					var url = window.rootPath + "/api/maintainItems/" +itemId;
					var data = {
						"maintainSchemeID": schemeID,
						"maintainPeriod": maintainPeriod,
						"maintainProject": maintainProject,
						"announcement": announcement,
						"memo": memo
					};
					jQuery.ajax({
						url:encodeURI(url),
						type:'patch',
						data: JSON.stringify(data),
						dataType: 'json',
						contentType: 'application/json;charset=utf-8',
						success: function (data) {
							jQuery("#itemId").val('');
							jQuery("#maintainPeriod").val('');
							jQuery("#maintainProject").val('');
							jQuery("#announcement").val('');
							jQuery("#memo").val('');
							serverItemData.schemeID=schemeID;
							serverItemTable.draw(false);
							jQuery(".saveItemBtn").attr("disabled", false);
						}
					});
				}
			}else{
			 $.springLemonDialog({
				content: '请完善项目信息！',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
			}
		}
		jQuery(".saveItemBtn").attr("disabled", false);
    });
	jQuery(function () { $('#maintainSchemeModal').on('hide.bs.modal', function () {
		serverSchemeTable.draw(true);
        })
     });
	//列表中的全选
    $("#checkAllItem").click(function(){
    	var check = $(this).prop("checked");
        $(".checkchildItem").prop("checked", check);
	});
	});
});
});